#include "xgraphicsview.h"
#include <QCloseEvent>
#include <QDebug>
#include <QToolTip>

XGraphicsView::XGraphicsView(QWidget* parent)
    : QGraphicsView(parent)
{
    m_hruler = new XRuleBar(Qt::Horizontal,this,this);
    m_hruler->setVisible(false);
    m_vruler = new XRuleBar(Qt::Vertical,this,this);
    m_vruler->setVisible(false);
    setAttribute(Qt::WA_DeleteOnClose);
}

void XGraphicsView::zoomIn()
{
    scale(1.1, 1.1);
    updateRuler();
}

void XGraphicsView::zoomOut()
{
    scale(1 / 1.1, 1 / 1.1);
    updateRuler();
}

void XGraphicsView::setRuleBarVisible(bool visible)
{
    if(visible)
    {
        m_hruler->setVisible(true);
        m_vruler->setVisible(true);
    }
    else
    {
        m_hruler->setVisible(false);
        m_vruler->setVisible(false);
    }
}

void XGraphicsView::wheelEvent(QWheelEvent* event)
{
    if (event->modifiers() & Qt::ControlModifier) {
        if (event->angleDelta().y() > 0) {
            zoomIn();
        } else {
            zoomOut();
        }
    } else {
        QGraphicsView::wheelEvent(event);
    }
}

void XGraphicsView::mouseMoveEvent(QMouseEvent* event)
{
    m_hruler->updatePosition(event->pos());
    m_vruler->updatePosition(event->pos());
    QGraphicsView::mouseMoveEvent(event);
}

void XGraphicsView::resizeEvent(QResizeEvent* event)
{
    QGraphicsView::resizeEvent(event);
    m_hruler->resize(this->size().width()- RULER_SIZE - 1,RULER_SIZE);
    m_hruler->move(RULER_SIZE,0);
    m_vruler->resize(RULER_SIZE,this->size().height() - RULER_SIZE - 1);
    m_vruler->move(0,RULER_SIZE);
    updateRuler();
}

void XGraphicsView::scrollContentsBy(int dx, int dy)
{
    QGraphicsView::scrollContentsBy(dx, dy);
    updateRuler();
}
void XGraphicsView::updateRuler()
{
    if ( scene() == 0) return;
    QRectF viewbox = this->rect();
    QPointF offset = mapFromScene(scene()->sceneRect().topLeft());
    //qDebug()<<"viewbox: "<<viewbox;
    //qDebug()<<"offset: "<<offset;
    double factor =  1./transform().m11();
    double lower_x = factor * ( viewbox.left()  - offset.x() + RULER_SIZE);
    double upper_x = factor * ( viewbox.right() - offset.x());//-RULER_SIZE

    m_hruler->setRange(lower_x,upper_x,upper_x - lower_x );
    m_hruler->update();

    double lower_y = factor * ( viewbox.top() - offset.y() + RULER_SIZE) ;
    double upper_y = factor * ( viewbox.bottom() - offset.y() );

    m_vruler->setRange(lower_y,upper_y,upper_y - lower_y );
    m_vruler->update();
//    qDebug()<<QPoint(lower_x,upper_x) << QPoint(lower_y,upper_y);
//    qDebug()<<"factor: "<<factor;
    //qDebug()<<viewbox<<QPoint(lower_x,upper_x) << QPoint(lower_y,upper_y) << offset;
}
